package com.kbook.tool;

import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;


public class Tools {

	private static DateFormat dateFormatOne = new SimpleDateFormat(
			"yyyy/MM/dd HH:mm");
	private static DateFormat dateFormatTwo = new SimpleDateFormat("yyyyMMdd");
	private static DateFormat dateFormatThree = new SimpleDateFormat("HHmm");
	private static DateFormat dateFormatFour = new SimpleDateFormat(
			"yyyy/MM/dd HH:mm:ss");
	private static DateFormat dateFormatFive = new SimpleDateFormat(
			"yyyy年MM月dd日 E HH:mm");
	private static DateFormat dateFormatSix = new SimpleDateFormat("yyyy/MM/dd");
	private static DateFormat dateFormatServen = new SimpleDateFormat(
			"yy/MM/dd");

	private static Random rand = null;
	private static char[] numAndLetters = null;
	private static Object initLock = new Object();

	public static String encodeUrl(String url) {
		// return url;
		try {
			return java.net.URLEncoder.encode(url, "UTF-8");
		} catch (Exception e) {
			return null;
		}
	}

	public static String decodeUrl(String url) {
		// return url;
		try {
			return java.net.URLDecoder.decode(url, "UTF-8");
		} catch (Exception e) {
			return null;
		}
	}

	public static String formatDate(Date date) {
		// DateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm");

		return dateFormatOne.format(date);
	}

	public static String formatDate(long date) {
		// DateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm");
		Date dateTime = new Date(date);
		return dateFormatOne.format(dateTime);
	}

	public static String formatDateToString(Date date) {

		// SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		return dateFormatTwo.format(date);
	}

	public static String formatHourToString(Date date) {

		// SimpleDateFormat sdf = new SimpleDateFormat("HHmm");
		return dateFormatThree.format(date);
	}

	public static String formatTimeStamp(Date date) {
		// DateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

		return dateFormatFour.format(date);
	}

	public static String getChineseDate(Date date) {
		// DateFormat format = new SimpleDateFormat("yyyy年MM月dd日 E HH:mm");

		String chineseDate = dateFormatFive.format(date);
		chineseDate = chineseDate.replace("Mon", "星期一").replace("Tue", "星期二")
				.replace("Wed", "星期三").replace("Thu", "星期四").replace("Fri",
						"星期五").replace("Sat", "星期六").replace("Sun", "星期日");

		return chineseDate;
	}

	public static String formatFloat(Float data, String formatter) {
		DecimalFormat format = null;

		if (StringUtils.isEmpty(formatter)) {
			formatter = "###,###,##0.00";
		}

		format = new DecimalFormat(formatter);

		return format.format(data);
	}

	public static String formatDouble(double data, String formatter) {
		DecimalFormat format = null;

		if (StringUtils.isEmpty(formatter)) {
			formatter = "###,###,##0.00";
		}

		format = new DecimalFormat(formatter);

		return format.format(data);
	}

	public static String formatByte(int data) {
		String result = "";

		double sizeByM = data / (1024 * 1024 + 0d);
		if (sizeByM >= 1.0) {
			result = Tools.formatDouble(sizeByM, "###,###,##0.##") + "MB";
		} else {
			double sizeByK = data / (1024 + 0d);
			result = Tools.formatDouble(sizeByK, "###,###,##0.##") + "KB";
		}

		return result;
	}

	public static String dateToString(Date date) {
		// SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
		if (date == null)
			return "";
		String d = "";
		d = dateFormatSix.format(date);
		return d;
	}

	public static String dateTimeToString(Date date) {
		// SimpleDateFormat sdf = new SimpleDateFormat("yy/MM/dd");
		if (date == null)
			return "";
		String d = "";
		d = dateFormatServen.format(date);
		return d;
	}

	public static Date formatStringToDate(String date) {

		// SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
		Date d = null;
		try {
			d = dateFormatSix.parse(date);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return d;
	}

	public static Date formatStringDate(String date) {

		// SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		Date d = null;
		try {
			d = dateFormatFour.parse(date);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return d;
	}

	public static int getTotalPage(int totalNum, int pageSize) {
		if (totalNum <= 0 || pageSize <= 0) {
			return 0;
		}

		int totalPage = totalNum / pageSize;
		if ((totalNum % pageSize) != 0) {
			totalPage += 1;
		}
		return totalPage;
	}

	public static String removeStr(String sourceStr, String toRemoved) {
		return StringUtils.replace(sourceStr, "," + toRemoved + ",", ",");
	}

	public static int ParseInt(String strValue) {
		int result = -1;
		if (StringUtils.isEmpty(strValue)) {
			return result;
		}

		try {
			result = Integer.parseInt(strValue);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}

		return result;

	}

	public static long parseLong(String strValue) {
		long result = -1;

		if (StringUtils.isEmpty(strValue)) {
			return result;
		}

		try {
			result = Long.parseLong(strValue);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}

		return result;
	}

	public static short parseShort(String strValue) {
		short result = -1;

		if (StringUtils.isEmpty(strValue)) {
			return result;
		}

		try {
			result = Short.parseShort(strValue);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}

		return result;
	}

	public static String getSex(Integer sex) {
		String result = "男";

		if (sex == null) {
			return result;
		}

		if (sex == 0) {
			result = "女";
		} else if (sex == 1) {
			result = "男";
		} else if (sex == 2) {
			result = "保密";
		}

		return result;
	}

	public static int[] getPageInfo(int pageSize, int page, int totalSize) {
		int[] result = new int[2];
		if (pageSize == -1) {
			pageSize = 10;
		}

		if (page == -1) {
			page = 1;
		}

		int firstResult = (page - 1) * pageSize;

		if (firstResult >= totalSize) {
			result[0] = 0;
			result[1] = 0;

			return result;
		}
		int toIndex = (firstResult + pageSize) > totalSize ? totalSize
				: (firstResult + pageSize);
		result[0] = firstResult;
		result[1] = toIndex;

		return result;
	}

	/**
	 * 判断是否字母、数字及下划线
	 * 
	 * @param name
	 * @return
	 */
	public static boolean isNameMatchRule(String name) {
		if (name == null)
			return false;
		Pattern pattern = Pattern.compile("[A-Za-z0-9_]+");
		Matcher matcher = pattern.matcher(name);
		return matcher.matches();
	}

	/**
	 * 判断是否为汉字
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isChinese(String str) {
		return java.util.regex.Pattern.matches("[\u4E00-\u9FA5]", str);
	}

	public static boolean isNickNameMatchRule(String nickName) {
		int len = nickName.length();
		for (int i = 0; i < len; i++) {
			String str = "";
			str = nickName.substring(i, i + 1);
			if (isChinese(str) || isNameMatchRule(str)) {
				continue;
			} else {
				return false;
			}
		}
		return true;
	}

	public static String replace(String toReplace, String[] params) {
		String result = toReplace;

		for (int i = 0; i < params.length; i++) {

			result = result.replaceFirst("A", params[i]);
		}

		return result;
	}

	public static String getType(String type) {

		if (type == null || "".equals(type))
			return "";
		String[] temp;
		if (type.contains("；"))
			temp = type.split("；");
		else
			temp = type.split("-");
		if (temp.length > 1)
			return temp[1].trim();
		return temp[0];
	}

	/**
	 * Check if the input is number.
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isNumber(String str) {
		Pattern pattern = Pattern.compile("[0-9]*");
		return pattern.matcher(str).matches();
	}

	public static boolean isSameDay(Date date, Date compareDate) {
		if (date.getYear() == compareDate.getYear()
				&& date.getMonth() == compareDate.getMonth()
				&& date.getDate() == compareDate.getDate()) {
			return true;
		}

		return false;
	}

	public static int dateInterval(Date date, Date compareDate) {
		if (isSameDay(date, compareDate)) {
			return 0;
		}

		int interval = (int) (compareDate.getTime() - date.getTime())
				/ (24 * 60 * 60 * 1000);
		return (interval + 1);
	}

	/**
	 * Calculate which horoscope he/she is by his/her birthday.
	 * 
	 * @param month
	 * @param day
	 * @return
	 */
	public static String getAstro(int month, int day) {
		String s = "魔羯水瓶双鱼牡羊金牛双子巨蟹狮子处女天秤天蝎射手魔羯";
		int[] arr = { 20, 19, 21, 21, 21, 22, 23, 23, 23, 23, 22, 22 };
		int pos = month * 2 - (day < arr[month - 1] ? 2 : 0);
		return s.substring(pos, pos + 2);
	}

	/**
	 * 产生激活码
	 * 
	 * @param length
	 * @return
	 */
	public static String generateActiveCode(int length) {

		if (length < 1)
			return null;
		if (rand == null) {
			synchronized (initLock) {
				rand = new Random();
				numAndLetters = ("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
						.toCharArray();
			}
		}
		char[] randBuffer = new char[length];
		for (int i = 0; i < randBuffer.length; i++) {
			randBuffer[i] = numAndLetters[rand.nextInt(61)];
		}
		return new String(randBuffer);
	}

	public static int parseInt(String strValue) {
		int result = -1;
		if (StringUtils.isEmpty(strValue)) {
			return result;
		}

		try {
			result = Integer.parseInt(strValue);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}

		return result;

	}
	
	public static String replaceSpecialCharater(String content){
		String result="";
		result=content.replaceAll(" ", "&nbsp;&nbsp;&nbsp;")
		              .replaceAll("\r\n", "<br>");
		return result;
	}
}
